package com.merry.boot.converter;

import com.merry.boot.bean.User;
import org.springframework.http.HttpInputMessage;
import org.springframework.http.HttpOutputMessage;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.http.converter.HttpMessageNotWritableException;

import java.io.IOException;
import java.io.OutputStream;
import java.util.List;

/**
 * @author msi
 * 自定义的converter：想要自定义messageConverter只需要实现HttpMessageConverter接口即可。
 * 将该自定义converter注入到webmvc的配置中，即在 WebMvcConfigurationSupport的实现类中添加即可。
 */
public class MyMessageConverter implements HttpMessageConverter<User> {

    /**
     * 这个converter是否支持读。
     * @param aClass
     * @param mediaType
     * @return
     */
    @Override
    public boolean canRead(Class<?> aClass, MediaType mediaType) {
        return false;
    }

    /**
     * converter是否支持写
     * @param aClass
     * @param mediaType
     * @return
     */
    @Override
    public boolean canWrite(Class<?> aClass, MediaType mediaType) {
        return aClass.isAssignableFrom(User.class);
    }

    /**
     * 获取所有messageConverter支持的媒体类型。
     * 所以我们需要将这个converter支持的媒体类型放到这个容器中，这里以 application/x-merry 为例
     * @return
     */
    @Override
    public List<MediaType> getSupportedMediaTypes() {
        return MediaType.parseMediaTypes("application/x-merry");
    }

    @Override
    public User read(Class<? extends User> aClass, HttpInputMessage httpInputMessage) throws IOException, HttpMessageNotReadableException {
        return null;
    }

    @Override
    public void write(User user, MediaType mediaType, HttpOutputMessage httpOutputMessage) throws IOException, HttpMessageNotWritableException {
        //自定义协议数据的写出
        String date=user.getName();
        //将数据写出去
        OutputStream body = httpOutputMessage.getBody();
        body.write(date.getBytes());
    }
}
